<?php

include_once 'UseRedis.php';

class UseMysql
{
	public $host = 'localhost';
	public $port = '3306';
	public $user = 'root';
	public $pwd  = 'root';
	public $dbname  = 'db_chat';

	public function getConnect()
	{
		$con =  new Mysqli($this->host, $this->user, $this->pwd, $this->dbname, $this->port);
		$con->set_charset('utf8');
		return $con;
	}

	/**
	 * @param $info
	 * @return array
	 * 聊天消息插入
	 * 'sendUser'  'receivedUser'  'message'  'messageType'
	 */
	public function setChatInfo($info)
	{
		$return = array();
		try{

			if (empty($info['userSend']) || empty($info['userReceived'])) {
				throw new Exception('消息为空!');
			}
			$sql = sprintf(
				"insert into tb_chat(user_send, user_received, message, message_type, date) values('%s', '%s', '%s', '%s', '%s')",
				$info['userSend'],
				$info['userReceived'],
				$info['message'],
				$info['type'],
				$this->getMicroTime()
			);
			$db = $this->getConnect();
			$result = $db->query($sql);

			$return['error'] = 0;
			$return['data']  = $result;

		} catch (Exception $e) {
			$return['error'] = 1;
			$return['message'] = $e;
			//打印日志
		}
		return $return;
	}

	/**
	 * @param $info
	 * @return array
	 * 聊天消息获取（一对一）
	 * 'user1' 'user2' page pageCount
	 */
	public function getChatInfoAll($info)
	{
		$return = array();
		try{

			if (empty($info['user1']) || empty($info['user2'])) {
				throw new Exception('用户为空!');
			}
			if (empty($info['page']) || empty($info['pageCount'])) {
				$info['page'] = 1;
				$info['pageCount'] = 30;
			}
			$start = ($info['page'] - 1) * $info['pageCount'];


			$sql = sprintf(
				"select * from tb_chat where user_send in ('%s', '%s')  AND user_received in ('%s', '%s') AND user_send != user_received order by date DESC LIMIT %s, %s",
				$info['user1'],
				$info['user2'],
				$info['user2'],
				$info['user1'],
				$start,
				$info['pageCount']
			);
			$db = $this->getConnect();
			$result = $db->query($sql);
			$result = $this->dealResult($result);

			$return['error'] = 0;
			$return['data']  = $result;

		} catch (Exception $e) {
			$return['error'] = 1;
			$return['message'] = $e;
			//打印日志
		}
		return $return;
	}

	/**
	 * @param $info
	 * @return array
	 * 聊天消息获取（一对多，只取一条）
	 * 'user' 'userList'
	 */
	public function getChatInfoOne($info)
	{
		$return = array();
		try{
			if (empty($info['user']) || empty($info['userList'])) {
				throw new Exception('用户为空!');
			}

			$sql = sprintf(
				"SELECT *  FROM tb_chat a1 WHERE EXISTS 
					(SELECT 1 FROM tb_chat a2  WHERE a2.user_received = a1.user_received  
					AND a2.user_send = a1.user_send
					AND ( 
						(a2.user_received IN (%s) AND a2.user_send IN(%s)) OR
						(a2.user_received IN (%s) AND a2.user_send IN(%s))
               		) HAVING MAX(a2.date)=a1.date);",
				$info['user'],
				implode(',', $info['userList']),
				implode(',', $info['userList']),
				$info['user']
			);
			$db = $this->getConnect();
			$result = $db->query($sql);
			$result = $this->dealResult($result);

			$chatList = array();
			foreach ($result as $key => $val) {
				if ($val['user_send'] == $info['user']) {
					$chatList[$val['user_received']] = $val;
				}
				if ($val['user_received'] == $info['user']) {
					$chatList[$val['user_send']] = $val;
				}
			}

			$return['error'] = 0;
			$return['data']  = $chatList;

		} catch (Exception $e) {
			$return['error'] = 1;
			$return['message'] = $e;
			//打印日志
		}
		return $return;
	}

	/**
	 * 批量获取用户信息
	 * @param array $info
	 * @return array
	 */
	public function getUserInfoList($info = array())
	{
		$return = array();
		try{
			if (empty($info['userList'])) {
				throw new Exception('用户列表为空!');
			}
			$info1 = array(
				'db'   => '1',
				'key'  => $info['userList'],
			);
			$redis = new UseRedis();
			$res   = $redis->mGetRedis($info1);
			if (!empty($res) && !empty($res['found'])) {
				foreach ($res['found'] as $key => $val) {
					$res['found'][$key] = json_decode($val,true);
				}
			}
			if (empty($res['found'])) {
				$res['found'] = array();
			}

			//没有从redis找到就先从数据库中取出， 然后存入redis
			$rett = array();
			if (!empty($res['notFound'])) {

				$sql = sprintf(
					'select * from tb_user where userid in (%s)',
					implode(',', $res['notFound'])
				);
				$db = $this->getConnect();
				$result = $db->query($sql);
				$result = $this->dealResult($result);

				if (!empty($result)) {
					$redis = new UseRedis();
					$inRedis = array();
					foreach ($result as $key => $val) {
						$rett[$key] = $val;
						$inRedis[$key]['key'] = $val['userid'];
						$inRedis[$key]['val'] = json_encode($val);
					}
					$arr = array(
						'db'  => 1,
						'info' => $inRedis,
					);
					$redis->mSetRedis($arr);
				}
			}
			$return['error'] = 0;
			$return['message']['dataList'] = array_merge($res['found'], $rett);

		} catch (Exception $e) {
			$return['error'] = 1;
			$return['message'] = $e;
			//打印日志
		}
		return $return;
	}

	/**
	 * 批量获取用户信息
	 * @param array $info
	 * @return array
	 */
	public function getUserInfoByTel($info = array())
	{
		$return = array();
		try{
			if (empty($info['mobile'])) {
				throw new Exception('参数错误!');
			}
			$info1 = array(
				'db'   => '1',
				'key'  => 'bind_tel:'.$info['mobile'],
			);
			$redis = new UseRedis();
			$res = $redis->GetRedis($info1);
			if (!empty($res)) {
				$res = json_decode($res,true);
			}
			//没有从redis找到就先从数据库中取出， 然后存入redis
			if (empty($res)) {
				$res = array();
				$sql = sprintf(
					'select * from tb_user where bind_tel in (%s)',
					 $info['mobile']
				);

				$db = $this->getConnect();
				$result = $db->query($sql);
				$result = $this->dealResult($result);
				if (!empty($result)) {
					$res = $result[0];
					$redis = new UseRedis();
					$arr = array(
						'db'  => 1,
						'key' => 'bind_tel:'.$info['mobile'],
						'value' => json_encode($result[0])
					);
					$redis->SetRedis($arr);
				}
			}
			$return['error'] = 0;
			$return['message']['dataList'] = $res;

		} catch (Exception $e) {
			$return['error'] = 1;
			$return['message'] = $e;
			//打印日志
		}
		return $return;
	}


	public function login($mobile='')
	{
		$return = array();
		$return['error'] = 0;
		try {
			if (empty($mobile)) {
				throw new Exception('参数错误');
			}
			$sessoion = md5( rand(100,1000).'-'.md5(10000,10000));
			$sql = sprintf(
				'update tb_user set sessionKey = "%s" where bind_tel = "%s"',
				$sessoion,
				$mobile
			);
			$db = $this->getConnect();
			$result = $db->query($sql);
			$return['data'] = $result;
		} catch (Exception $e) {
			$return['error'] = 1;
			$return['message'] = $e;
		}

		return $return;

	}

	public function register($mobile='')
	{
		$return = array();
		$return['error'] = 0;

		try {
			if (empty($mobile)) {
				throw new Exception('参数错误');
			}

			$sql = sprintf(
				"insert into tb_user(bind_tel) values('%s')",
				$mobile
			);
			$db = $this->getConnect();
			$result = $db->query($sql);
			$return['data']  = $result;

		} catch (Exception $e) {
			$return['error'] = 1;
			$return['data']  = $e;
		}

		return $return;

	}

	public function dealResult($result)
	{
		$data = array();
		while($row = $result->fetch_assoc()) {
			$data[] = $row;
		}
		return $data;
	}

	public function getMicroTime()
	{
		$mtime = explode(' ', microtime());
		$startTime = (float)sprintf('%.0f',(floatval($mtime[0])+floatval($mtime[1]))*1000);
		return $startTime;
	}
}

//$use = new UseMysql();
//
//$data = array(
//	'mobile' => '18372551588',
//);
//
//$a = $use->login('18372551588');
//var_dump($a);
